package engine.gameObject.collider;

import java.util.ArrayList;
import java.util.Arrays;

import engine.gameObject.GameObject;

public class BoundingSphere {
	private float radius;
	private float[] position;
	
	private ArrayList<BoundingSphere> children;
	private BoundingSphere origin;
	
	private boolean isResetted;
	
	public BoundingSphere(float radius, float[] position) {
		children = new ArrayList<BoundingSphere>();
		
		this.radius = radius;
		this.position = position;
	}
	
	public void addSphere(BoundingSphere sphere) {
		children.add(sphere);
	}
	
	public float[] getPosition() {
		return position;
	}
	
	public float getRadius() {
		return radius;
	}
	
	public void setRadius(float radius) {
		this.radius = radius;
	}
	
	public ArrayList<BoundingSphere> getChildren() {
		return children;
	}
	
	public BoundingSphere copy() {
		BoundingSphere copy = new BoundingSphere(radius, Arrays.copyOf(position, position.length));
		
		if(origin == null) {
			copy.origin = this;
		} else {
			copy.origin = origin;
		}
		
		for(BoundingSphere child: children) {
			copy.addSphere(child.copy());
		}
		
		return copy;
	}
	
	public void reset() {
		isResetted = true;
		
		for(BoundingSphere child: children) {
			child.reset();
		}
	}
	
	public void setOrigin(BoundingSphere origin) {
		this.origin = origin;
	}
	
	public BoundingSphere getOrigin() {
		return origin;
	}
	
	public void updatePosition(GameObject parent) {
		if(!isResetted) {
			return;
		}
		
		//TODO update the position according to the position of the gameobject. 
		
		if(origin != null) {
			position[0] = parent.getPosX() + parent.getScaleX() * origin.getPosition()[0];
			position[1] = parent.getPosY() + parent.getScaleY() * origin.getPosition()[1];
			position[2] = parent.getPosZ() + parent.getScaleZ() * origin.getPosition()[2];
			
			radius = origin.getRadius() * Math.max(Math.max(parent.getScaleX(), parent.getScaleY()), parent.getScaleZ());
		} else {
			position[0] = parent.getPosX();
			position[1] = parent.getPosY();
			position[2] = parent.getPosZ();
		}
		
		isResetted = false;
	}
}
